package com.ybg.bookmanages.controller;

import com.ybg.bookcommons.dto.BorrowBookDTO;
import com.ybg.bookcommons.dto.ReturnDTO;
import com.ybg.bookmanages.module.vo.BookinfosVO;
import com.ybg.bookmanages.services.BookinfosService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@RestController
@RequestMapping("/manage")
public class ManagerCtrl {

     @Resource
    private BookinfosService bookinfosService;
    /**
     * 将用户传来的时间 按照格式封装成java.util.Date
     **/
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 添加图书
     **/
    @RequestMapping(value = "/addbook", method = RequestMethod.POST)
    public ReturnDTO addBook(BookinfosVO book, MultipartFile file) {
     // bookinfosService.addBook(book, file);
        bookinfosService.addBook(book, file);
        return ReturnDTO.builder().status("success").message("新增图书添加成功").build();
    }

/**
 * 根据isbn对库存进行-1操作 并判断库存为0则下架
 **/
@RequestMapping(value = "/deList")
public ReturnDTO deList( String isbn,  String demagereason) {
    System.out.println(isbn);
    boolean res = bookinfosService.damageBook(isbn, demagereason);
    if(res){
        return ReturnDTO.builder().status("success").message("图书破损操作成功").build();
    }else {
        return ReturnDTO.builder().status("fail").message("图书破损操作失败").build();
    }
}

    /**
     * 借阅图书
     **/
    @RequestMapping("/borrow/{isbn}/{carid}")
    public ReturnDTO borrow(@PathVariable String isbn,@PathVariable String carid ) {
        boolean res = bookinfosService.borrowBook(isbn, carid);
        return ReturnDTO.builder().status("success").message("借阅成功").build();
    }

    /*归还图书*/
    @RequestMapping("/back/{isbn}/{carid}")
    public BorrowBookDTO back(@PathVariable String isbn,@PathVariable String carid) {
        BorrowBookDTO bbdto = bookinfosService.backBook(isbn, carid);
        return bbdto;
    }
}
